# -*- coding:UTF-8 -*-
import datetime

import threading
import time
import random
from multiprocessing import Queue

from spider_xue.account import set_account_is_yes
from db import *
from spider_xue.logger import logging
from spider_xue.settings import FIFTEEN_SECOND, INFO, DEBUG, ERROR, NINE_TIME_STAMP, NINE_AND_HALF_SECOND, STEP
from spider_xue.thread_file import mission_day, mission_five, missionThread, putIPThread
from spider_xue.utils import get_day_not_today, get_five_not_today, send_msg, reset_all_account, reset_all_ip, break_flag

queueLock = threading.Lock()
eflag = 1


def play(mission_fuc):
    if break_flag():
        return
    reset_all_account()
    reset_all_ip()

    workQueue = Queue(100)
    all_stocks = stock_db.find({"use": 1})
    all_stocks = [i for i in all_stocks]
    for i in range(0, len(all_stocks), STEP):
        workQueue.put(all_stocks[i:i+STEP])

    flagQueue = Queue(1)
    workQueueIP = Queue(300)
    thread2 = putIPThread(1, 'putIPThread', workQueueIP, new_ip_db, flagQueue)
    thread2.start()

    thread_id = 2
    while True:
        if break_flag():
            break
        accounts = account_db.find({"is": 0, "use": 1})
        thread_list = []
        for account in accounts:
            set_account_is_yes(account)
            threadx = missionThread(
                thread_id, account, workQueue, workQueueIP, mission_fuc)
            time.sleep(random.random())
            threadx.start()
            thread_list.append(threadx)
            thread_id += 1

        thread_num = len(threading.enumerate())
        logging.info(f"heart beating ...... thread num {thread_num}")
        for stop_thread in thread_list:
            stop_thread.join()

        if workQueue.empty():
            flagQueue.put(1)
            break


def play_for_one(mission_fuc):
    if break_flag():
        return

    workQueue = Queue(400)
    all_stocks = stock_db.find({"use": {"$gte": 1, '$lte': 4}, 'today': {"$gt": 0, '$lt': 10}})
    all_stocks = [i for i in all_stocks]
    print(len(all_stocks))
    for i in range(0, len(all_stocks), STEP):
        workQueue.put(all_stocks[i:i+STEP])

    flagQueue = Queue(1)
    workQueueIP = Queue(300)
    thread2 = putIPThread(1, 'putIPThread', workQueueIP,
                          new_ip_db, new_ip_txt_db, dirty_ip_db, flagQueue)
    thread2.start()

    thread_id = 2
    while True:
        if break_flag():
            break
        accounts = account_db.find({"is": 0, "use": 1})
        thread_list = []
        count = 0
        for account in accounts:
            if workQueue.qsize() <= 1 and count > 2:
                break
            if workQueue.qsize() <= 2 and count > 4:
                break
            if workQueue.qsize() <= 3 and count > 6:
                break
            if workQueue.qsize() <= 4 and count > 8:
                break
            if workQueue.qsize() <= 5 and count > 10:
                break

            threadx = missionThread(
                thread_id, account, workQueue, workQueueIP, mission_fuc)
            time.sleep(random.random())
            threadx.start()
            thread_list.append(threadx)
            thread_id += 1
            count += 1

        for stop_thread in thread_list:
            stop_thread.join()
        thread_num = len(threading.enumerate())
        logging.info(f"heart beating ...... thread num {thread_num}")
        if workQueue.empty():
            flagQueue.put(1)
            break


def play_for_one_no_flag(mission_fuc):
    reset_all_account()
    reset_all_ip()
   
    workQueue = Queue(400)
    all_stocks = stock_db.find({"use": 1, 'today': {"$gt": 0, '$lt': 10}})
    all_stocks = [i for i in all_stocks]
    print(len(all_stocks))
    for i in range(0, len(all_stocks), STEP):
        workQueue.put(all_stocks[i:i+STEP])

    flagQueue = Queue(1)
    workQueueIP = Queue(300)
    thread2 = putIPThread(1, 'putIPThread', workQueueIP,
                          new_ip_db, new_ip_txt_db, dirty_ip_db, flagQueue)
    thread2.start()

    thread_id = 2
    while True:
        accounts = account_db.find({"is": 0, "use": 1})
        thread_list = []
        count = 0
        for account in accounts:
            if workQueue.qsize() <= 1 and count > 2:
                break
            if workQueue.qsize() <= 2 and count > 4:
                break
            if workQueue.qsize() <= 3 and count > 6:
                break
            if workQueue.qsize() <= 4 and count > 8:
                break
            if workQueue.qsize() <= 5 and count > 10:
                break
            # set_account_is_yes(account)
            threadx = missionThread(
                thread_id, account, workQueue, workQueueIP, mission_fuc)
            time.sleep(random.random())
            threadx.start()
            thread_list.append(threadx)
            thread_id += 1
            count += 1

        for stop_thread in thread_list:
            stop_thread.join()
        thread_num = len(threading.enumerate())
        logging.info(f"heart beating ...... thread num {thread_num}")
        if workQueue.empty():
            flagQueue.put(1)
            break


def play_for_five_without_flag(mission_fuc, all=1):

    # reset_all_account()
    # reset_all_ip()
    
    workQueue = Queue(400)
    if all:
        all_stocks = stock_db.find({"use": {"$gte": 1, '$lte': 5}})
        all_stocks = [i for i in all_stocks]
    else:
        all_stocks = get_five_not_today()
    print(len(all_stocks))
    for i in range(0, len(all_stocks), STEP):
        workQueue.put(all_stocks[i:i+STEP])
    
    flagQueue = Queue(1)
    workQueueIP = Queue(300)
    thread2 = putIPThread(1, 'putIPThread', workQueueIP,
                          new_ip_db, new_ip_txt_db, dirty_ip_db, flagQueue)
    thread2.start()

    thread_id = 2
    while True:
        accounts = account_db.find({"is": 0, "use": 1})
        thread_list = []
        count = 0
        for account in accounts:
            if workQueue.qsize() <= 1 and count > 2:
                break
            if workQueue.qsize() <= 2 and count > 4:
                break
            if workQueue.qsize() <= 3 and count > 6:
                break
            if workQueue.qsize() <= 4 and count > 8:
                break
            if workQueue.qsize() <= 5 and count > 10:
                break
            count += 1
            set_account_is_yes(account)
            threadx = missionThread(
                thread_id, account, workQueue, workQueueIP, mission_fuc)
            time.sleep(random.random())
            threadx.start()
            thread_list.append(threadx)
            thread_id += 1

        for stop_thread in thread_list:
            stop_thread.join()
        thread_num = len(threading.enumerate())
        logging.info(f"heart beating ...... thread num {thread_num}")
        if workQueue.empty():
            flagQueue.put(1)
            break

#####################################


def play_for_day_without_flag(mission_fuc, all=1):

    # reset_all_account()
    # reset_all_ip()
   
    workQueue = Queue(600)
    if all:
        all_stocks = stock_db.find({"use": {"$gte": 1, '$lte': 5}})
        all_stocks = [i for i in all_stocks if 'ST' not in i['name']]
    else:
        all_stocks = get_day_not_today()
    print(len(all_stocks))
    for i in range(0, len(all_stocks), STEP):
        workQueue.put(all_stocks[i:i+STEP])

    flagQueue = Queue(1)
    workQueueIP = Queue(300)
    thread2 = putIPThread(1, 'putIPThread', workQueueIP,
                          new_ip_db, new_ip_txt_db, dirty_ip_db, flagQueue)
    thread2.start()

    thread_id = 2
    while True:
        accounts = account_db.find({"is": 0, "use": 1})
        thread_list = []
        count = 0
        for account in accounts:
            if workQueue.qsize() <= 1 and count > 2:
                break
            if workQueue.qsize() <= 2 and count > 4:
                break
            if workQueue.qsize() <= 3 and count > 6:
                break
            if workQueue.qsize() <= 4 and count > 8:
                break
            if workQueue.qsize() <= 5 and count > 10:
                break
            count += 1

            set_account_is_yes(account)
            threadx = missionThread(
                thread_id, account, workQueue, workQueueIP, mission_fuc)
            time.sleep(random.random())
            threadx.start()
            thread_list.append(threadx)
            thread_id += 1

        for stop_thread in thread_list:
            stop_thread.join()
        thread_num = len(threading.enumerate())
        logging.info(f"heart beating ...... thread num {thread_num}")
        if workQueue.empty():
            flagQueue.put(1)
            break


def set_nine_time_stamp():
    t5 = int(time.mktime(datetime.date.today().timetuple())) + \
        NINE_AND_HALF_SECOND
    settings_db.update_one({"name": "nine_timestamp"}, {
                           "$set": {'timestamp': t5}}, upsert=True)
    t15 = int(time.mktime(datetime.date.today().timetuple())) + FIFTEEN_SECOND
    settings_db.update_one({"name": "fifteen_timestamp"}, {
                           "$set": {'timestamp': t15}}, upsert=True)


def set_account():
    account_db.delete_many({"use": 1})
    tmp = []
    count = 0
    with open('spider_xue/cookies.txt', 'r') as f:
        # coo = f.readline()
        for coo in f.readlines():
            for i in range(25):
                d = {
                    "phone": f"chrome_x{count}",
                    "cookies": coo.strip(),
                    "use": 1,
                    "is": 0,
                }
                tmp.append(d)
                count += 1
    account_db.insert_many(tmp)


